<?php

namespace app\service\sms;

use AlibabaCloud\SDK\Dysmsapi\V20170525\Dysmsapi;
use AlibabaCloud\Tea\Utils\Utils;
use app\model\PhoneCode;
use app\model\SysSetting;
use Darabonba\OpenApi\Models\Config;
use AlibabaCloud\SDK\Dysmsapi\V20170525\Models\SendSmsRequest;
use AlibabaCloud\SDK\Dysmsapi\V20170525\Models\QuerySendDetailsRequest;

class ALiSms
{
    /**
     * 使用AK&SK初始化账号Client
     * @param string $accessKeyId
     * @param string $accessKeySecret
     * @return Dysmsapi
     */
    public static function createClient($accessKeyId, $accessKeySecret){
        $config = new Config([]);
        $config->accessKeyId = $accessKeyId;
        $config->accessKeySecret = $accessKeySecret;
        return new Dysmsapi($config);
    }

    /**
     * @param string $access_key_id
     * @param string $access_key_secret
     * @param string[] $args
     * @return array
     */
    public static function send($access_key_id, $access_key_secret, $args){
        $client = self::createClient($access_key_id, $access_key_secret);

        // 1.发送短信
        $sendReq = new SendSmsRequest([
            "phoneNumbers" => @$args[0],
            "signName" => @$args[1],
            "templateCode" => @$args[2],
            "templateParam" => @$args[3]
        ]);
        $sendResp = $client->sendSms($sendReq);
        $code = $sendResp->body->code;
        if (!Utils::equalString($code, "OK")) {
            return dataReturn(-1, lang("错误信息:") . $sendResp->body->message . "");
        }
        $bizId = $sendResp->body->bizId;
        // 2. 等待 10 秒后查询结果
//        Utils::sleep(10000);
        // 3.查询结果
//        $phoneNums = explode(',', @$args[0]);
//        $phoneNums = StringUtil::split(@$args[0], ",", -1);
//        $errorMsg = '';
//        $successMsg = '';
//        foreach($phoneNums as $phoneNum){
//            $queryReq = new QuerySendDetailsRequest([
//                "phoneNumber" => Utils::assertAsString($phoneNum),
//                "bizId" => $bizId,
//                "sendDate" => Time::format("yyyyMMdd"),
//                "sendDate" => date('Ymd'),
//                "pageSize" => 10,
//                "currentPage" => 1
//            ]);
//            $queryResp = $client->querySendDetails($queryReq);
//            $dtos = $queryResp->body->smsSendDetailDTOs->smsSendDetailDTO;
//            // 打印结果
//            foreach($dtos as $dto){
//                if (Utils::equalString("" . (string) ($dto->sendStatus) . "", "3")) {
//                    $successMsg .= $dto->phoneNum . " 发送成功，接收时间: " . $dto->receiveDate;
//                }
//                else if (Utils::equalString("" . (string) ($dto->sendStatus) . "", "2")) {
//                    $errorMsg .= $dto->phoneNum . " 发送失败";
//                }
//                else {
//                    $errorMsg .= $dto->phoneNum . " 正在发送中...";
//                }
//            }
//        }
        return dataReturn(0, lang('验证码发送成功'));
    }

    /**
     * 发送单条验证码信息
     * @param array $data ['phone' => '', 'code' => '', 'expired_time' =>'']
     * @return array
     */
    public static function sendOneAuthMsg($data): array
    {
        $sysSettingModel = new SysSetting();
        $access_key_id = $sysSettingModel->where(['title' => 'ali_access_key_id', 'seller_id' => $data['seller_id']])->value('value');
        $access_key_secret = $sysSettingModel->where(['title' => 'ali_access_key_secret', 'seller_id' => $data['seller_id']])->value('value');
        $signName = $sysSettingModel->where(['title' => 'ali_sign_name', 'seller_id' => $data['seller_id']])->value('value');
        $templateCode = $sysSettingModel->where(['title' => 'ali_template_code', 'seller_id' => $data['seller_id']])->value('value');

        if (empty($access_key_id) || empty($access_key_secret) || empty($signName) || empty($templateCode)) {
            return dataReturn(-5, lang('请完整填写阿里短信配置'));
        }

        $templateParam = "{\"code\":\"{$data['code']}\"}";
        $phone = $data['phone'];
        try {
            $res = self::send($access_key_id, $access_key_secret, [$phone, $signName, $templateCode, $templateParam]);
        } catch (\Exception $e) {
            return dataReturn(-3, $e->getMessage(), $e->getTrace());
        }
        return $res;
    }
}